package zut.edu.cn.concertticketmanagementsystem.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import zut.edu.cn.concertticketmanagementsystem.Dao.OrderDetailDao;
import zut.edu.cn.concertticketmanagementsystem.Dao.OrderFormDao;
import zut.edu.cn.concertticketmanagementsystem.Dao.TicketDao;
import zut.edu.cn.concertticketmanagementsystem.dto.CarDTO;
import zut.edu.cn.concertticketmanagementsystem.dto.OrderDTO;
import zut.edu.cn.concertticketmanagementsystem.entity.OrderDetail;
import zut.edu.cn.concertticketmanagementsystem.entity.OrderForm;
import zut.edu.cn.concertticketmanagementsystem.entity.Ticket;
import zut.edu.cn.concertticketmanagementsystem.enums.OrderStatusEnum;
import zut.edu.cn.concertticketmanagementsystem.enums.PayStatusEnum;
import zut.edu.cn.concertticketmanagementsystem.enums.ResultEnum;
import zut.edu.cn.concertticketmanagementsystem.exception.SellException;
import zut.edu.cn.concertticketmanagementsystem.service.OrderFormService;
import zut.edu.cn.concertticketmanagementsystem.service.Ticketservice;
import zut.edu.cn.concertticketmanagementsystem.utils.KeyGenarate;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: heroma
 * Date: 6/22/19
 * Time: 4:45 PM
 * Description: No Description
 */
@Slf4j
@Service
public class OrderFormServiceImpl implements OrderFormService {
    @Autowired
    private Ticketservice ticketService;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private OrderFormDao orderFormDao;
    @Autowired
    private TicketDao ticketDao;

    @Override
    public OrderDTO creat(OrderDTO orderDTO) {
        String orderId= KeyGenarate.genUniqueKey();
        BigDecimal orderAmount=new BigDecimal(BigInteger.ONE.ZERO);
//        List<CarDTO>carDTOList=new ArrayList<>();
        Double money=0.0;
        //查询商品（数量，价格）
        for(OrderDetail orderDetail:orderDTO.getOrderDetailList()){
            Ticket productInfo=ticketService.findOneById(Integer.parseInt(orderDetail.getProductId()) );
            if(productInfo==null){
                log.info("商品不存在！");
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIT);
            }
            //计算订单总价
            money+=productInfo.getT_price()*orderDetail.getProductQuantity();
            BigDecimal orderAmount1= new BigDecimal(money);
            orderAmount=orderAmount1;
            //订单详情入库
//            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetail.setDetailId(KeyGenarate.genUniqueKey());
            orderDetail.setOrderId(orderId);
            orderDetail.setProductName(productInfo.getT_name());
            orderDetail.setProductPrice(new BigDecimal(productInfo.getT_price()));


            orderDetailDao.save(orderDetail);
//            CarDTO carDTO=new CarDTO(orderDetail.getProductId(),orderDetail.getProductQuantity());
//            carDTOList.add(carDTO);
        }

        //写入订单数据库（orderMaster和orderDetail）
        OrderForm orderMaster=new OrderForm();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);

        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderFormDao.save(orderMaster);
        //扣库存
        List<CarDTO> carDTOList= orderDTO.getOrderDetailList().stream().map(e ->
                new CarDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
//        ticketService.decreaseStock(carDTOList);
        for(CarDTO carDTO:carDTOList) {
            Ticket productInfo = ticketDao.findAllById(Integer.parseInt(carDTO.getProductId()));

            if (productInfo == null) {
                log.info("库存不正确！");
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            Integer result = productInfo.getT_remaincount() - carDTO.getProductQuantity();
            if (result < 0) {
                log.info("库存错误！");
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setT_remaincount(result);
            ticketDao.save(productInfo);
        }
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderForm orderMaster=orderFormDao.findByOrderId(orderId);
        if(orderMaster==null){
            log.info("订单不存在！");
        }
        List<OrderDetail>orderDetailList=orderDetailDao.findByOrderId(orderId);
        if(CollectionUtils.isEmpty(orderDetailList)){
            log.info("订单详情表不存在！");
        }
        OrderDTO orderDTO=new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public List<OrderForm> findList(String buyerName) {
        return orderFormDao.findByBuyerName(buyerName);
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderForm orderMaster=new OrderForm();

        //判断订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【取消订单】 订单状态错误，orderId={}，orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderForm updateResult=orderFormDao.save(orderMaster);
        if(updateResult==null){
            log.error("【取消订单】 更新失败， orderMaqster={}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        //返回库存
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("【取消订单】 订单中午商品详情，orderDTO={}",orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CarDTO>carDTOList=orderDTO.getOrderDetailList().stream()
                .map(e -> new CarDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
//        ticketService.increaseStock(carDTOList);
        for(CarDTO carDTO:carDTOList){
            Ticket productInfo=ticketDao.findAllById(Integer.parseInt(carDTO.getProductId()));
            if(productInfo==null){
                log.info("库存不正确！");
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            Integer result=productInfo.getT_remaincount()+carDTO.getProductQuantity();
            productInfo.setT_remaincount(result);
            ticketDao.save(productInfo);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.info("【完结订单】 订单状态不正确，orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISH.getCode());
        OrderForm orderMaster=new OrderForm();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderForm updateResult=orderFormDao.save(orderMaster);
        if(updateResult==null){
            log.error("【完结订单】 更新失败， orderMaqster={}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.info("【订单支付成功】 订单状态不正确，orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //判断支付状态
        if(!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
            log.info("【订单支付成功】 订单支付状态不正确，orderDTO={},",orderDTO);
            throw new SellException(ResultEnum.ORDER_PAY_SATUS_ERROR);
        }
        //修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderForm orderMaster=new OrderForm();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderForm updateResult=orderFormDao.save(orderMaster);
        if(updateResult==null){
            log.error("【订单支付成功】 更新失败， orderDTO={}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Transactional
    public void deleteByOrderId(String orderId) {
        List<OrderDetail> orderDetails= orderDetailDao.findByOrderId(orderId);
        for (OrderDetail orderDetail1:orderDetails){
            orderDetailDao.deleteById(orderDetail1.getDetailId());
        }
        orderFormDao.deleteById(orderId);
    }

    @Override
    public List<OrderForm> list() {
        return orderFormDao.findAll();
    }
}

